package com.zzl.car.service;

import com.zzl.car.entity.User;
import com.zzl.car.exception.ZdpException;
import com.zzl.car.mapper.UserMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoveCarScoresService loveCarScoresService;
    @Autowired
    private RedisTemplate redisTemplate;

    public User getUser(String telephone,String password){
        return userMapper.getUserByLogin(telephone,password);
    }

    /*
    * 验证验证码，只需要传入电子邮箱
    * */
    public String emailVerify(String email,String myVerify){
        String key = "verify-"+email;
        String verify =(String) redisTemplate.opsForValue().get(key);
        if(verify==null){
            throw new ZdpException(1006,"验证失败");
        }
        if(!verify.equals(myVerify)){
            throw new ZdpException(1003,"验证码错误");
        }
        return "验证成功";
    }


    /*
    * 用户注册
    * */
    public User registerUser(User user){
        //先判断该用户名是否存在
        User userByTelephone = userMapper.getUserTelephoneByTelephone(user.getTelephone());
        if(userByTelephone!=null)
            return null;
        //若不存在，就插入
        // 顺便计算一下爱车指数分
        Integer loveCarScore = loveCarScoresService.caculateLoveCarScores();
        userMapper.insertUser(user.getTelephone(),user.getPassword(),user.getEmail(),loveCarScore);
        return userMapper.getUserByLogin(user.getTelephone(),user.getPassword());
    }
    /*
    * 修改用户信息
    * */
    public String updateUserInfo(User user){
        //更新后需要更新缓存的哥
        Integer integer = userMapper.updateUser(user);
        if(integer!=0){
            // 修改成功
            redisTemplate.opsForValue().set(user.getTelephone(),user);
            return "修改成功";
        }
        // 修改失败
        throw new ZdpException(1005,"修改失败");

    }

    /*
    * 根据手机号获取到用户信息
    * */
    public User getUserAllByTelephone(String telephone){

        return userMapper.getUserAllByTelephone(telephone);
    }
    /*
    * 获取用户信息，传入手机号
    * */
    public User getUserInfo(String telephone){
        User user = (User) redisTemplate.opsForValue().get("telephone");
        if(user!=null)
            return user;
        return userMapper.getUserAllByTelephone(telephone);
    }

}
